<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单数据调试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .debug-section { margin: 20px 0; padding: 15px; border: 1px solid #ccc; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        .debug-btn { padding: 8px 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; margin: 5px; }
        .debug-btn:hover { background: #0056b3; }
        .json-display { background: #f8f9fa; padding: 10px; border-radius: 4px; white-space: pre-wrap; font-family: monospace; }
    </style>
</head>
<body>
    <h1>订单数据调试页面</h1>
    
    <div class="debug-section">
        <h3>1. 用户认证状态</h3>
        <button class="debug-btn" onclick="checkAuthStatus()">检查认证状态</button>
        <div id="authStatus"></div>
    </div>
    
    <div class="debug-section">
        <h3>2. 测试订单API</h3>
        <button class="debug-btn" onclick="testOrdersAPI()">测试获取订单API</button>
        <div id="apiResult"></div>
    </div>
    
    <div class="debug-section">
        <h3>3. 创建新订单</h3>
        <button class="debug-btn" onclick="createNewOrder()">创建测试订单</button>
        <div id="createResult"></div>
    </div>
    
    <div class="debug-section">
        <h3>4. 刷新订单列表</h3>
        <button class="debug-btn" onclick="refreshOrders()">刷新订单列表</button>
        <div id="refreshResult"></div>
    </div>
    
    <div class="debug-section">
        <h3>5. 控制台日志</h3>
        <div id="consoleLog"></div>
    </div>

    <!-- 引入必要的脚本 -->
    <script src="js/api.js"></script>
    <script src="js/auth.js"></script>
    
    <script>
        // 重写console.log来显示在页面上
        const originalLog = console.log;
        const originalWarn = console.warn;
        const originalError = console.error;
        
        function addToConsole(message, type = 'info') {
            const logDiv = document.getElementById('consoleLog');
            const timestamp = new Date().toLocaleTimeString();
            logDiv.innerHTML += `<div class="${type}">[${timestamp}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }
        
        console.log = function(...args) {
            originalLog.apply(console, args);
            addToConsole(args.join(' '), 'info');
        };
        
        console.warn = function(...args) {
            originalWarn.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        console.error = function(...args) {
            originalError.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        // 检查认证状态
        function checkAuthStatus() {
            const statusDiv = document.getElementById('authStatus');
            try {
                const authToken = localStorage.getItem('authToken');
                const userData = JSON.parse(localStorage.getItem('currentUser') || '{}');
                const isAuthenticated = window.authManager ? window.authManager.isAuthenticated() : false;
                
                statusDiv.innerHTML = `
                    <div class="info">
                        <strong>认证Token:</strong> ${authToken || '无'}<br>
                        <strong>用户数据:</strong> ${JSON.stringify(userData, null, 2)}<br>
                        <strong>认证状态:</strong> ${isAuthenticated ? '已认证' : '未认证'}<br>
                        <strong>用户名:</strong> ${userData.username || '无'}
                    </div>
                `;
                
                console.log('认证状态检查:', {
                    authToken,
                    userData,
                    isAuthenticated
                });
            } catch (error) {
                statusDiv.innerHTML = '<div class="error">检查认证状态失败: ' + error.message + '</div>';
                console.error('检查认证状态失败:', error);
            }
        }
        
        // 测试订单API
        async function testOrdersAPI() {
            const resultDiv = document.getElementById('apiResult');
            try {
                console.log('开始测试订单API...');
                const result = await window.api.getOrders();
                
                resultDiv.innerHTML = `
                    <div class="success">API调用成功</div>
                    <div class="json-display">${JSON.stringify(result, null, 2)}</div>
                `;
                
                console.log('订单API结果:', result);
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">API调用失败: ' + error.message + '</div>';
                console.error('订单API调用失败:', error);
            }
        }
        
        // 创建新订单
        async function createNewOrder() {
            const resultDiv = document.getElementById('createResult');
            try {
                const orderData = {
                    items: [
                        {
                            productId: 'F002',
                            product_name: '测试商品',
                            price: 99.99,
                            quantity: 1
                        }
                    ],
                    shippingAddress: {
                        name: '测试用户',
                        phone: '13800138000',
                        address: '测试地址'
                    },
                    paymentMethod: 'alipay',
                    discount: 0
                };
                
                console.log('创建订单数据:', orderData);
                const result = await window.api.createOrder(orderData);
                
                if (result.success) {
                    resultDiv.innerHTML = `
                        <div class="success">订单创建成功</div>
                        <div class="json-display">${JSON.stringify(result.data, null, 2)}</div>
                    `;
                    console.log('订单创建成功:', result.data);
                } else {
                    resultDiv.innerHTML = '<div class="error">订单创建失败: ' + result.error + '</div>';
                    console.error('订单创建失败:', result.error);
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">创建订单错误: ' + error.message + '</div>';
                console.error('创建订单错误:', error);
            }
        }
        
        // 刷新订单列表
        async function refreshOrders() {
            const resultDiv = document.getElementById('refreshResult');
            try {
                console.log('刷新订单列表...');
                const result = await window.api.getOrders();
                
                if (result.success) {
                    const orders = result.data.orders || [];
                    resultDiv.innerHTML = `
                        <div class="success">订单列表刷新成功，共 ${orders.length} 个订单</div>
                        <div class="json-display">${JSON.stringify(orders, null, 2)}</div>
                    `;
                    console.log('订单列表:', orders);
                } else {
                    resultDiv.innerHTML = '<div class="error">刷新订单列表失败: ' + result.error + '</div>';
                    console.error('刷新订单列表失败:', result.error);
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">刷新订单列表错误: ' + error.message + '</div>';
                console.error('刷新订单列表错误:', error);
            }
        }
        
        // 页面加载完成后运行
        window.addEventListener('load', () => {
            console.log('订单数据调试页面加载完成');
            
            // 模拟用户登录
            const userData = {
                username: 'Mike',
                user_id: 'USER001',
                email: 'mike@example.com',
                phone: '1234567890',
                user_type: 'Customer',
                token: 'test-token-mike'
            };
            
            localStorage.setItem('currentUser', JSON.stringify(userData));
            localStorage.setItem('userData', JSON.stringify(userData));
            localStorage.setItem('authToken', userData.token);
            
            if (window.authManager) {
                window.authManager.currentUser = userData;
                window.authManager.isLoggedIn = true;
                window.authManager.userType = userData.user_type;
            }
            
            console.log('模拟用户登录完成:', userData);
        });
    </script>
</body>
</html>
